import { Component, OnInit } from '@angular/core';
import { LocalStorage } from '@core/local.storage';
import { NzMessageService } from 'ng-zorro-antd';
import { HandoverBusiness } from './handover.business';
import { environment } from '../../../../environments/environment';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import * as _ from 'lodash';

@Component({
  selector: 'app-handover',
  templateUrl: './handover.readonly.component.html',
  styleUrls: ['./handover.readonly.component.less']
})
export class handoverRdComponent implements OnInit {

  // admin   whdwd
  date = null;

  dateFormat = 'yyyy年MM月dd日   （EEEE）';
  thisMonth = '';
  loading = false;
  data_backup: object;
  tcjhb = {
    title: '',
    repairid: '',
    tcjhbVisible: false,
    style: { width: '1800px', height: '650px' },
    data: [],
    backupData: [],
    loadingData: false,
    itemsRepairDayTotal: 0,
    repairDayPageIndex: 1,
    repairDayAllowEdit: true,
    id: ''
  };
  data = {
    datePickerDate: this.getToday(),
    today: this.getToday(),
    head: [],
    aqxx: {
      gt: [],
      pt: [],
      qtxx: [],
      raqxxfxzz: [],
      raqfxts: [],
    }, // 安全信息
    scxx: {// 生产信息方面
      dfk: [],
      zgszz: [],
      dzz: [],
      safeinfo: '本日新增追踪信息x条，申请销号x条，x月份追踪累计x条，现遗留x条',
      trackinfo: '本日新增x条，销号x条，x月追踪累计x条 ，现遗留x条',
      copuinfo: '广南车间x项，弥勒车间x项',
      dayinfo: '曲靖北车间x项，广南车间x项、弥勒车间x项',
      tcjhqk: {// 天窗计划情况
        // 昨日施工计划:
        zrsgjh: [],
        jrsgjh: [],
        zrsgphjh: [],
        jrsgphjh: [],
        zrwxjh: {
          I: {
            gt: [{}],
            pt: [{}],
          },
          II: {
            gt: [{}],
            pt: [{}],
          },
        },
        jrwxjh: {
          I: {
            gt: [{}],
            pt: [{}],
          },
          II: {
            gt: [{}],
            pt: [{}],
          },
        },
        // 紧急修计划
        jjxjh: []
      },
      // 车载数据换装及升级情况
      czsj: [],
      // 分路不良统计分析：
      flbltj: [],
      dwjh: {
        total: 0,
        content: ''
      },
      // 领导、干部行踪：
      ldxz: [],
      zzph: [{//
        ID: 'str', // 这个是需要的可以是任意字符串,用于getArraysDiff()中进行修改或新增判断
        IMP_TRACK_INFO: '', // 总公司
        IMP_TRACK_INFO_DUAN: '', // 段
        TIANCHUAN_INFO: '', // 配合施工信息 昨日施工计划
        DIANWAI: '',
        PROD_INFO: '',
        EMER_INFO: '',
        TC_INFO: '',
      }], // 追踪配合//总公司、集团公司日安全分析重点追踪信息+
      // 段日安全分析重点追踪信息反馈+ks
      // 昨日施工配合计划+
      // 今日施工配合计划
      // 的统计信息保存
      jrzzph: [{// 追踪配合
        ID: 'str', // 这个是需要的可以是任意字符串,用于getArraysDiff()中进行修改或新增判断
        TIANCHUAN_INFO: '', // 配合施工信息,仅传这个字段 今日
        TC_INFO: '',
      }]
    },
    qtxx: {
      // 安全预警书统计情况：
      aqyjstj: [],
      // 安全风险通知书统计
      aqfxtzstj: [],
      // 交班重点工作要求
      jbyq: [],
    },
  };


  user: any = {
    cj: [],
    cj_filter: [],
    cz: [],
    cz_filter: [],
    saveAble: true,
    loading: false,
  };



  collapseTitles = {
    head: '人员安排',
    aqxx: `一、安全信息：${this.trueStatistic(this.data.aqxx.gt) +
      this.trueStatistic(this.data.aqxx.pt) +
      this.trueStatistic(this.data.aqxx.qtxx) +
      this.trueStatistic(this.data.aqxx.raqxxfxzz)}件`,
    // aqxx: `一、安全信息：${this.data.aqxx.gt.length + this.data.aqxx.pt.length}件`,
    scxx: `二.生产信息方面`,
    qtxx: `三.其它信息`, // 日安全信息分析追踪
  };

  constructor(
    public ls: LocalStorage,
    private message: NzMessageService,
    private handoverBusiness: HandoverBusiness,
    private http: _HttpClient,
    private datePipe: DatePipe
  ) { }

  userInfo = JSON.parse(this.ls.get('loginInfo'));

  ngOnInit() {
    // this.setThisMonth();
    this.handoverBusiness.setHandoverCmp({
      data: this.data,
      tcjhb: this.tcjhb,
      user: this.user,
      data_backup: this.data_backup,
      message: this.message,
      editable: true,
      loading: this.user.loading,
      backupData: this.backupData,
      getDataDiff: this.getDataDiff,
      getObjsDiff: this.getObjsDiff,
      getArraysDiff: this.getArraysDiff,
      stringEqual: this.stringEqual,
      parsePropDate: this.parsePropDate,
      isObjEmpty: this.isObjEmpty,
    });
    const param = this.ls.getObject('param_handoverRd');
    if (param.date) {
      this.data.datePickerDate = param.date;
      this.data.today = param.date;
      this.ls.remove('param_handoverRd');
    }
    this.handoverBusiness.getAllInfo();
  }

  getToday(num: number = 0, dateValue?: string | Date) {
    let todayDate: Date;
    if (dateValue) {
      // if (typeof dateValue == 'string') {
      //     todayDate = new Date(dateValue);
      // } else if (dateValue instanceof Date) {
      //     todayDate = dateValue;
      // }
      todayDate = new Date(dateValue);
    } else {
      todayDate = new Date();
    }
    todayDate.setDate(todayDate.getDate() + num);
    return this.datePipe.transform(todayDate, 'yyyy-MM-dd');
  }

  getTheDate(num: number = 0) {
    const _date = this.data.today;
    return this.getToday(num, _date);

  }

  setThisMonth() {
    const month = new Date().getMonth() + 1;
    if (month < 10) {
      this.thisMonth = '0' + month;
    } else {
      this.thisMonth = '' + month;
    }
  }

  trueStatistic(rows) {
    let trueStat: number = rows.length;
    if (rows && rows.length <= 2) {
      rows.forEach(row => {
        if (this.isObjEmpty(row)) {
          trueStat--;
        }
      });
    }
    return trueStat;
  }

  /**
   * 判断对象是否业务上为空
   * 判断 对象本身存在但是所有属性都空认为是空对象
   *  或者对象没有属性
   */
  isObjEmpty(obj: object) {
    let allEmpty = true;
    if (JSON.stringify(obj) == '{}') {
      allEmpty = true;
    } else {
      const values = Object.values(obj);
      for (let i = 0; i < values.length; i++) {
        const value = values[i];
        if (value) {
          allEmpty = false;
          break;
        }
      }
    }
    return allEmpty;
  }


  addRow(arr: Array<any>, elType?: string) {
    if (elType == 'string') {
      arr.push('');
    } else {
      arr.push({});
    }
  }

  deleteRow(arr: Array<object>, index: number) {
    arr.splice(index, 1);
  }

  backupData() {
    this.data_backup = JSON.parse(JSON.stringify(this.data));
  }

  stringEqual(obj1: object, obj2: object) {
    const str1 = JSON.stringify(obj1);
    const str2 = JSON.stringify(obj2);
    return str1 == str2;
  }

  getDataDiff() {
    const dif = this.getObjsDiff(this.data, this.data_backup);
    return dif;
  }

  getObjsDiff(obj1: object, obj2: object) {
    if (!obj1 || !obj2) {
      return;
    }
    const diffs = {};
    for (const key in obj1) {
      if (obj1.hasOwnProperty(key)) {
        const el1 = obj1[key];
        const el2 = obj2[key];
        // let el1Str = JSON.stringify(el1);
        // let el2Str = JSON.stringify(el2);
        if (!this.stringEqual(el1, el2)) {
          if (el1 instanceof Array && el2 instanceof Array) {
            const arrDif = this.getArraysDiff(el1, el2);
            if (arrDif) {
              diffs[key] = arrDif;
            }
          } else if (typeof el1 == 'object' && typeof el2 == 'object') {
            diffs[key] = this.getObjsDiff(el1, el2);
          } else {

          }

        }
      }
    }
    if (JSON.stringify(diffs) == '{}') {
      return;
    } else {
      return diffs;
    }
  }


  parsePropDate(param) {
    for (const pkey in param) {
      if (param.hasOwnProperty(pkey)) {
        const pEl = param[pkey];
        if (pEl instanceof Date) {   
          param[pkey] = this.datePipe.transform(pEl, 'yyyy-MM-dd');
        }
      }
    }
  }


  getArraysDiff(arr1: object[], arr2: object[]) {
    const adds = [], edits = [], dels = [];
    const diff = {
      adds, edits, dels
    };
    arr1.forEach((arr1El: any) => {
      const id = arr1El.ID;
      if (id) {// 存在
        const el = arr2.find((arr2El: any) => arr2El.ID == id);
        if (el) {
          this.parsePropDate(arr1El);
          if (!this.stringEqual(arr1El, el)) {// 修改过
            edits.push(arr1El);
          }
        }
      } else {// 不存在，新增
        if (JSON.stringify(arr1El) != '{}') {
          adds.push(arr1El);
        }
      }
    });
    arr2.forEach((arr2El: any) => {
      const id = arr2El.ID;
      const el = arr1.find((arr1El: any) => arr1El.ID == id);
      if (!el) {// 不存在，删除
        dels.push(arr2El);
      }
    });
    if (!adds.length && !edits.length && !dels.length) {
      return;
    } else {
      return diff;
    }
  }

  dateChange(e: Event) {
    this.data.today = this.getToday(0, this.data.datePickerDate);
    this.handoverBusiness.getAllInfo();
  }

  showTcjhb(row, j, i) {
    const ID = row.ID;
    this.tcjhb.tcjhbVisible = true;
    this.handoverBusiness.getTcjhb(ID);
    let _date, _line;
    if (row.REPAIR_DATE) {
      _date = row.REPAIR_DATE;
    } else {
      if (j == 0) {
        _date = this.getTheDate();
      } else {
        _date = this.getTheDate(1);
      }
    }
    if (row.LINE) {
      _line = row.LINE;
    } else {
      if (i == 0 || i == 2) {
        _line = '高铁';
      } else {
        _line = '普铁';
      }
    }
    this.tcjhb.title = `${_date}维修日计划(${_line})`;
  }

  tcjhbCancel() {
    this.tcjhb.tcjhbVisible = false;
  }

  saveTcjhb() {
    this.handoverBusiness.saveTcjhb();
  }

  updateRepairDayData(pageNum: number) {
    const tcjhb = this.tcjhb, REPAIRID = tcjhb.id;
    tcjhb.repairDayPageIndex = pageNum;
    tcjhb.loadingData = true;
    this.repairDayPlan({ REPAIRID }, { pageNum })
      .subscribe(res => {
        if (res.type === 'success') {
          const response = res.response;
          tcjhb.itemsRepairDayTotal = response.totalCount;
          tcjhb.data = response.data;
          tcjhb.repairDayAllowEdit = _.isNil(response.modifyRight) ? 1 : response.modifyRight;
          tcjhb.loadingData = false;
        }
      });
  }

  // 天窗计划分页
  repairDayPlan(body, param) {
    const url = environment.apiBase + '/csmis/duty/repairTC.jwt';
    return this.http.post(url, body, param);
  }
}
